package com.xinqi.modules.exam.common.delayed;

import com.xinqi.modules.exam.common.delayed.dto.ExamMqMessage;
import com.xinqi.modules.exam.common.enums.ExamQueueEnum;
import com.xinqi.modules.mq.delay.client.DelayMessageClient;
import com.xinqi.modules.mq.delay.dto.MqDelayMessageDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 测评延时队列服务
 * <p>发布定时测试任务</p>
 * <p>删除定时测评任务</p>
 *
 * @author linkai
 * @date 2023/7/7
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ExamDelayQueueService {
    private final DelayMessageClient delayMessageClient;

    @Value("${rocketmq.examTopic}")
    public String examTopic;

    /**
     * 发布任务
     *
     * @param examQueue 测评队列
     * @param examId    测评id
     * @param dateTime  定时时间
     */
    public void publishTask(ExamQueueEnum examQueue, Long examId, LocalDateTime dateTime) {
        log.info("====> 发布延时任务，队列名称={}，examId={}，dateTime={}", examQueue.queueName(), examId, dateTime);
        delayMessageClient.create(getDelayMessage(examQueue, examId, dateTime));
    }

    /**
     * 移除任务
     *
     * @param examQueue 测评队列
     * @param examId    测评id
     */
    public void removerTask(ExamQueueEnum examQueue, Long examId) {
        log.info("====> 移除延时任务， 队列名称={}，examId={}", examQueue.queueName(), examId);
        delayMessageClient.delete(mqId(examQueue, examId));
    }

    /**
     * 更新定时任务
     *
     * @param examQueue 测评队列
     * @param examId    测评id
     * @param dateTime  定时时间
     */
    public void updateTask(ExamQueueEnum examQueue, Long examId, LocalDateTime dateTime) {
        log.info("====> 更新延时任务， 队列名称={}，examId={}", examQueue.queueName(), examId);
        removerTask(examQueue, examId);
        publishTask(examQueue, examId, dateTime);
    }

    public MqDelayMessageDTO getDelayMessage(ExamQueueEnum examQueue, Long examId, LocalDateTime dateTime) {
        MqDelayMessageDTO message = new MqDelayMessageDTO();
        message.setTopic(examTopic);
        message.setKey(mqId(examQueue, examId));
        message.setTag(examQueue.queueName());
        message.setArrivalTime(dateTime);
        message.setBody(ExamMqMessage.as(examQueue.queueName(), examId.toString()));
        return message;
    }

    public MqDelayMessageDTO getMessage(String topic, ExamQueueEnum examQueue, Long examId) {
        MqDelayMessageDTO message = new MqDelayMessageDTO();
        message.setTopic(topic);
        message.setKey(mqId(examQueue, examId));
        message.setTag(examQueue.queueName());
        message.setBody(ExamMqMessage.as(examQueue.queueName(), examId.toString()));
        return message;
    }

    public String mqId(ExamQueueEnum examQueue, Long examId) {
        return String.format("%s_%s", examQueue.queueName(), examId);
    }
}
